#! /usr/bin/env python3
# -*- coding:utf-8 -*-

from io import StringIO
from io import BytesIO
from student import Student
# import shutil
import os
import pickle
import json
import logging
logging.basicConfig(level=logging.ERROR)


'io操作示例'

f = None
try:
    f = open("o7rm.py", 'r')
    print(f.read())
except IOError as e:
    logging.error("IOError")
finally:
    if f:
        f.close()

# with 能保证自动调用close方法
with open("orm.py", 'r', encoding='utf8') as f:
    # print(f.read())
    print("readline:", f.readline().strip())
    print("readlines:", f.readlines()[0].strip())
    print("read 100:", f.read(1).strip())


# with open("test.py", 'w', encoding='utf8') as f:
    # f.writelines("testsssssssssssssssssssssss")

# StringIO操作字符流
f = StringIO()
print(f.write("hello world"))
print(f.getvalue())

f = StringIO("kladjiad\nadjaspdjoaisda\njadjosajd\n")
print(f.readlines())


# ByteIO操作字节流
f = BytesIO()
print(f.write("哈哈哈哈哈哈哈哈哈哈哈".encode("utf8")))
print(f.getvalue().decode("utf8"))

# os相关
print(os.name, "java_home:", os.environ.get("java_home"))
path = os.path.join(os.path.abspath(""), "os")  # 处理文件路径分隔符
print("文件路径分割：", os.path.split(path))
print("文件后缀分割：", os.path.splitext(path))
# 创建文件夹 删除文件夹(文件夹为空)
# os.mkdir(path)
# os.rmdir(path)
# 文件重命名删除
# os.rename(path, "ss")
# os.remove(path)
# 删除文件夹（包括子文件）
# shutil.rmtree(path)

print([x for x in os.listdir('.') if os.path.isfile(x)
       and os.path.splitext(x)[1] == '.py'])

# 练习 打印目录及子目录中包含filters的文件


def printDir(path, filters):
    listD = os.listdir(path)
    for x in listD:
        pathc = os.path.join(path, x)
        if os.path.isfile(pathc) and x.find(filters) >= 0:
            print(pathc)
        elif os.path.isdir(pathc):
            printDir(pathc, filters)


printDir(os.path.abspath(".."), "te")

# 序列化反序列化 pickling unpickling
dic = dict(name='dean', age=20)
with open('pickle.txt', 'wb') as f:
    f.write(pickle.dumps(dic))
    pickle.dump(dic, f)
with open('pickle.txt', 'rb') as f:
    print(pickle.load(f))
    print(pickle.loads(f.read()))

# json 使用方法同pickle
print(json.dumps(dic))
print(json.dumps(Student('dean', 20), default=lambda obj: obj.__dict__))
